import {
  AbstractTabs,
  Paragraph,
  Title,
  WithMargins,
  C11Gallery,
  C14Table,
  AbstractButton,
  C26InlineButtonWrapper,
  AbstractImage,
  BulletList,
  AbstractVideo,
} from "@/components";
import { TabSectionData } from "@/data/shared/entityShapes";
import { useApplicationInfo } from "@/store/applicationDataContext";
import { getDiscoverTabId, switchTab } from "@/utils/navigation";
import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import style from "./index.module.scss";

type TabMenuProps = {
  tabContent: TabSectionData;
};

const C10TabSection = ({ tabContent }: TabMenuProps) => {
  const { dispatch } = useApplicationInfo();

  // Filtered, should never happen, but CMS can't guarantee type
  const onlyActualTabContent = tabContent.filter(
    (tabcontentItem) => tabcontentItem.type === "labelPage"
  );

  const oneLevelUnnested = onlyActualTabContent.flatMap(
    (tabDetailsParentArr) => tabDetailsParentArr.content
  );

  return (
    <View className={style["tabbed-section-wrapper"]}>
      <AbstractTabs
        tabs={oneLevelUnnested.map((tabDetails) => tabDetails.title)}
      >
        {/* Tabs */}
        {oneLevelUnnested.map((tabDetailsObject, idx) => (
          <View key={idx}>
            {tabDetailsObject.child.map(
              (tabDetailsSection, tabDetailsSectionIdx) => {
                switch (tabDetailsSection.type) {
                  case "title":
                    return (
                      <WithMargins
                        key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}`}
                      >
                        <Title>{tabDetailsSection.content}</Title>
                      </WithMargins>
                    );
                  case "content":
                    return tabDetailsSection.content
                      .split(/\n/)
                      .map((paragraphCopy, contentIdx) => {
                        return (
                          <WithMargins
                            key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}-${contentIdx}`}
                          >
                            <Paragraph>{paragraphCopy}</Paragraph>
                          </WithMargins>
                        );
                      });
                  case "unorderedList":
                    return (
                      <WithMargins
                        key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}`}
                      >
                        <BulletList
                          bulletListItems={tabDetailsSection.content.split(
                            /\n/
                          )}
                        />
                      </WithMargins>
                    );
                  case "picture":
                    return (
                      <WithMargins
                        key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}`}
                      >
                        <AbstractImage
                          src={tabDetailsSection.content}
                          type="none"
                          className={style["inline-image"]}
                        />
                      </WithMargins>
                    );
                  case "video":
                    return (
                      <WithMargins
                        key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}`}
                      >
                        {tabDetailsSection.content.map((videoObj) => (
                          <View className={style["tab-video"]} style={{ paddingBottom: `${videoObj.attHeight / videoObj.attWidth * 100}%` }}>
                            <AbstractVideo
                              style={{ position: "absolute", top: 0, left: 0, width: "100%", height: '100%' }}
                              objectFit="cover"
                              muted={false}
                              loop={false}
                              autoplay={false}
                              src={videoObj.value}
                            />
                          </View>
                        ))}
                      </WithMargins>
                    );
                  case "table":
                    return (
                      <WithMargins
                        key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}`}
                      >
                        <C14Table rowData={tabDetailsSection.content} />
                      </WithMargins>
                    );
                  case "atlas":
                    return (
                      <C11Gallery
                        key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}`}
                        images={tabDetailsSection.content.map(
                          (imgPathObj) => imgPathObj.value
                        )}
                      />
                    );
                  // Special hard-coded treatment for buttons
                  case "blueBGBTN":
                    if (tabDetailsSection.typeUse === "nav") {
                      return (
                        <WithMargins
                          key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}`}
                        >
                          <C26InlineButtonWrapper>
                            <AbstractButton
                              color="viking"
                              className={style["show-directions-cta"]}
                              onClick={() => {
                                Taro.openLocation({
                                  latitude: +tabDetailsSection.lat,
                                  longitude: +tabDetailsSection.lon,
                                  scale: 18,
                                  name: tabDetailsSection.address,
                                });
                              }}
                            >
                              {tabDetailsSection.content}
                            </AbstractButton>
                          </C26InlineButtonWrapper>
                        </WithMargins>
                      );
                    } else if (tabDetailsSection.typeUse === "jumpWx") {
                      return (
                        <WithMargins
                          key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}`}
                        >
                          <C26InlineButtonWrapper>
                            <AbstractButton
                              color="viking"
                              className={style["show-directions-cta"]}
                              onClick={() => {
                                let appId = tabDetailsSection.appid;
                                let path = tabDetailsSection.link;

                                Taro.navigateToMiniProgram({
                                  appId: appId, // 需要替换为正确的appId
                                  path: path, // 需要替换为正确的页面路径
                                  extraData: {
                                    // 可以传递给小程序的额外数据
                                  },
                                  fail: (err) => {
                                    console.log('err: ', err);
                                  }
                                  // 其他可能需要的配置项
                                });
                              }}
                            >
                              {tabDetailsSection.content}
                            </AbstractButton>
                          </C26InlineButtonWrapper>
                        </WithMargins>
                      );
                    } else if (tabDetailsSection.typeUse === "channelVideo") {
                      return (
                        <WithMargins
                          key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}`}
                        >
                          <C26InlineButtonWrapper>
                            <AbstractButton
                              color="viking"
                              className={style["show-directions-cta"]}
                              onClick={() => {
                                console.log('tabDetailsSection: ', tabDetailsSection);

                                wx.openChannelsActivity({
                                  feedId: tabDetailsSection.feedId,
                                  finderUserName: tabDetailsSection.finderUserName,
                                  success: res => {

                                  },
                                  fail: err => {

                                  }
                                })
                              }}
                            >
                              {tabDetailsSection.content}
                            </AbstractButton>
                          </C26InlineButtonWrapper>
                        </WithMargins>
                      );
                    }
                    break;
                  // Special hardcoded logic for underline button
                  case "underlineBTN":
                    return (
                      <WithMargins
                        key={`${tabDetailsSectionIdx}-${tabDetailsObject.title}`}
                      >
                        <View
                          className={style["course-discover-link"]}
                          onClick={() => {
                            if (tabDetailsSection.typeUse === 'jumpWx') {

                              let appId = tabDetailsSection.appid;
                              let path = tabDetailsSection.link;

                              Taro.navigateToMiniProgram({
                                appId: appId, // 需要替换为正确的appId
                                path: path, // 需要替换为正确的页面路径
                                extraData: {
                                  // 可以传递给小程序的额外数据
                                },
                                // 其他可能需要的配置项
                              });
                            } else if (tabDetailsSection.typeUse === "channelVideo") {
                              wx.openChannelsActivity({
                                feedId: tabDetailsSection.feedId,
                                finderUserName: tabDetailsSection.finderUserName,
                                success: res => {

                                },
                                fail: err => {

                                }
                              })
                            } else {
                              dispatch({
                                type: "DISCOVER_TAB",
                                data: {
                                  tab: getDiscoverTabId("course"),
                                },
                              });
                              switchTab("pages/discover/index");
                            }
                          }}
                        >
                          {tabDetailsSection.content}
                        </View>
                      </WithMargins>
                    );

                  default:
                    break;
                }
              }
            )}
          </View>
        ))}
      </AbstractTabs>
    </View>
  );
};

export default C10TabSection;
